/**
 * @description JsonSchema编辑器,编辑一个JsonSchema并保存 ,可用于 表单 和 页面 设计
 */
Rsd.define('Rsd.tool.JsonSchemaEditor', {
    extend: 'Rsd.zen.dialog.ListDialog',
    requires: [
        'Rsd.control.Grid',
        'Rsd.form.Label',
        'Rsd.form.Button'
    ],
    xtype: 'schema-editor', 
    readonly:false,    
    layout: 'vbox',
    width:'90%',
    height:'90%',
    autoLoad:true,
    toolbar:null,
    /**
     * 复杂属性显示模式：full:完全数据，simple:简单
     */
    model:'simple',
    form:{
        height:'100%',
        width:800,
        position:'right',
        titleField:'$id',
        title:"Schema详细信息:{{=$id}}"
    }, 
    /**
     * https://json-schema.org/understanding-json-schema/
     */
    allFields:
    [
        {
            name:"$id",
            label:'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;键值',
            readonly:true,
            width:'70%',
            ctrlStyle:{border:'0px',borderBottom:'1px grey solid'}
        }, 
        {
            name:"type",
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数据类型",
            readonly:true,
            width:'20%',
            ctrlStyle:{border:'0px',borderBottom:'1px grey solid'}
        },
        {
            name:"$ref",
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;引用",
            //readonly:true,
            width:'90%',
            ctrlStyle:{border:'0px',borderBottom:'1px grey solid'}
        },
        //$defs
        {
            name:"dependencies",
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;依赖",
            width:'90%',
            ctrlStyle:{border:'0px',borderBottom:'1px grey solid'}
        },
        {height:15,width:"100%",style:{backgroundImage:"linear-gradient(#eee,#fff"}},
        {
            name:"title",
            label:'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数据名称',
            width:'50%'
        },
        {
            width:'40%'
        },
        //UI 交互 录入控件
        {
            name:"xtype",//录入控件
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录入控件",
            for:"string",
            xtype:"combobox",
            dataSource:["text","number","date","image","combobox","combbox-enum"],
            width:'40%'
        },
         //UI 交互 录入控件
         {
            name:"xtype",//录入控件
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录入控件",
            for:"array",
            xtype:"combobox",
            dataSource:["list","grid","tree"],
            width:'40%'
        },
        //UI 交互 录入控件
        {
            name:"xtype",//录入控件
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录入控件",
            for:"object",
            xtype:"combobox",
            dataSource:["modelForm","JsonForm"],
            width:'40%'
        },
        //UI 视觉
        {name:"height",label:'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;编辑框高度',width:'25%'},
        {name:"width",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;编辑框宽度",width:'25%'},  
        {name:'labelStyle',label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;标签样式"},
        {name:'ctrlStyle',label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;控件样式"},
        //UI 交互 数据源
        {
            //关联录入控件的数据源
            name:"dstype",//录入控件
            label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;数&nbsp;&nbsp;据&nbsp;&nbsp;源",
            for:"string",
            xtype:"combobox",
            dataSource:[
                {text:"常用文字",value:'text'},
                {text:"图片",value:'image'},
                {text:"链接",value:'link'},
                {text:"枚举",value:'enum'},
                {text:"其他数据",value:"other"}
            ],
            width:'45%',
            onchange:'dstype_change'
        }, 
        {
            name:"enum",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;枚&nbsp;&nbsp举",
            for:"string",width:'45%',xtype:'combobox'
        },  
        {name:"description",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录入提示",width:'90%'},
        {name:"examples",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;示例数据",width:'90%',xtype:'json'},
       
        //"readonly" 
        //"writeOnly"
     
        //string
        {name:"minLength",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;最小长度",for:"string",width:'30%'},
        {name:"maxLength",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;最大长度",for:"string",width:'30%'}, 
        {name:"default",label:"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;默认值",for:"string",width:'30%'},
        {name:"pattern",label:"&nbsp;&nbsp;正则表达式",for:"string"},
        {name:"format",label:"&nbsp;&nbsp;&nbsp;格式化表达式",for:"string"}, 

        //number
        {name:"multipleOf",label:"&nbsp;&nbsp;&nbsp;是该值的倍数",for:"number",width:'20%'},
        {name:"maximum",label:"&nbsp;&nbsp;&nbsp;最大值",for:"number",width:'20%'},
        {name:"exclusiveMaximum",label:"&nbsp;&nbsp;&nbsp;不包含最大值",for:"number",width:'20%'},
        {name:"minimum",label:"&nbsp;&nbsp;&nbsp;最小值",for:"number",width:'20%'},
        {name:"exclusiveMinimum",label:"&nbsp;&nbsp;&nbsp;不包含最小值",for:"number",width:'20%'},
        {name:"default",label:"&nbsp;&nbsp;&nbsp;默认值",for:"number",width:'20%'},

         //对象类型 约束
        //{name:"properties",label:"属性",for:"object"},
        //patternProperties 属性名通过正则表达式匹配
        {name:"minProperties",label:"&nbsp;&nbsp;&nbsp;最少属性成员",for:"object",width:'20%'},
        {name:"maxProperties",label:"&nbsp;&nbsp;&nbsp;最多属性成员",for:"object",width:'20%'},
        {name:"required",label:"&nbsp;&nbsp;&nbsp;必填属性",for:"object",width:'50%'}, 
        {name:"additionalProperties",label:"&nbsp;&nbsp;&nbsp;其他属性Schema",for:"object",width:'90%',tip:'对象属性除properties设定schema之外，允许的其他schema'},

        //数组类型 约束
        //{name:"items",label:"数组元素Schema",for:"array"}, 
        {name:"minItems",label:"&nbsp;&nbsp;&nbsp;数组最小长度",for:"array",width:'30%'},
        {name:"maxItems",label:"&nbsp;&nbsp;&nbsp;数组最大长度",for:"array",width:'30%'},
        {name:"uniqueItems",label:"&nbsp;&nbsp;&nbsp;数组中元素唯一",for:"array",width:'30%'},
        {name:"additionalItems",label:"&nbsp;&nbsp;&nbsp;其他数组元素Schema",for:"array",width:'90%',tip:'数组元素除items设定schema之外，允许的其他schema'},

        //通用约束
        {height:15,width:"100%",style:{backgroundImage:"linear-gradient(#eee,#fff"}},
        {name:"allOf",label:"&nbsp;&nbsp;必须满所有子Schema",width:'90%'},
        {name:"anyOf",label:"&nbsp;&nbsp;满足其中一个或多个子Schema",width:'90%'},
        {name:"oneOf",label:"&nbsp;&nbsp;满足其中一个子Schema",width:'90%'},
        {name:"not",label:"&nbsp;&nbsp;不允许满足的子Schema",width:'90%'}
    ],
    /**
     * 属性列表
     */
    gridColumns:[
        {
            xtype:'template',
            text:'名称(代码)',
            align:'left',
            dataIndex:'title',
            width:'20%',
            format:'formatTitle',
            nobr:true
        },
        {
            dataIndex:"type",
            text: "类型",
            nobr:true,
            xtype:'enum',
            enum:[
                {code:'object',text:'Json对象',color:'blue'},
                {code:'array',text:'Json数组',color:'green'},
                {code:'string',text:'字符',color:'black'},
                {code:'number',text:'数字',color:'black'},
                {code:'date',text:'日期',color:'black'}
            ]
        }, 
        {xtype:'bool',dataIndex:"required",text: "必填"},
        {dataIndex:"default",text: "默认值"},
        {
            xtype:'template',
            align:'left',
            dataIndex:"examples",
            text: "示例数据",
            formatString:'描述：{{=description}}<br>示例：{{=examples}}',
            maxLength:'30%'
        },
        {
            xtype:'template',
            text:'编辑框大小',
            tip:'表单编辑时，编辑框大小',
            nobr:true,
            formatString:'{{=height}} * {{=width}}'
            
        }
    ], 
    /**
     * 
     */
    buttons:[{text:'保 存',label:false}],
     
    /*
     * */
    constructor: function JsonSchemaEditor(config) {

        config = config || {};
        this.apply(config);  
    },
    /**
     * 
     * @param {*} schema  jsonSchema
     */
    load:function load(schema)
    {
        if(schema && schema instanceof Rsd.data.JsonSchema)
        {
            throw new Error('schema is not instanceof Rsd.data.JsonSchema');
            //return;
        }
        this.data = (schema||this.data||{}); 
        if(!this.data)
        {
            return;
        }
        this.data.height = this.data.height ||'auto';
        this.data.width = this.data.width ||'auto';
        this.data.childIndex = 0;
        var _list = [this.data]; 
        //递归
        var _fn = function(_properties,childIndex)
        {
            for (var i in _properties) {
                var p = _properties[i];
                p.title = p.title;
                p.height = p.height ||'auto';
                p.width = p.width ||'auto';
                p.childIndex = childIndex;
                _list.push(p);

                if(p.type=='object')
                { 
                    _fn(p.properties,childIndex+1);
                    continue;
                }
                if(p.type =='array')
                {
                    if(Rsd.isArray(p.items))
                    { 
                        _fn(p.items,childIndex+1);
                    }
                    else
                    {
                        _fn(p.items.properties,childIndex+1);
                    }
                    continue;
                }   
            }
        }
        //入口
        _fn(this.data.properties,1);
        //加载数据
        this.callParent(_list);
    },
    /**
     * 
     * @param {*} sender 
     * @param {*} row 
     */
    formatTitle:function formatTitle(row)
    { 
        var list = [Rsd.blankspace(row["childIndex"]*4)];
        list.push(Rsd.text(row["title"]+'('+row["$id"]+')'));
        if(row["type"] == 'array' && Rsd.isObject(row["items"]))
        {
            list.push(Rsd.text('[结构相同]',{color:'red'},'数组元素使用相同Schema'))
        } 
        return list;
    },
    /**
     * @description 查看记录详细信息
     * @param {*} row 
     * @param {*} readonly 
     */
    showItem:function showItem(row,readonly)
    {
        this.formFields = [];
        for(var i in this.allFields)
        {
            var f = this.allFields[i];
            if(!f.for || row['type'] == f.for)
            {
                this.formFields.push(f);
            } 
        }
        this.callParent(row,readonly);
    },
    /**
     * 
     * @param {*} sender 
     * @param {*} e 
     */
    dstype_change:function(sender,e)
    {
        var form = sender.parent;
        var enumCombobox = form.getItemByName('enum');
        enumCombobox.setDisabled(sender.getValue()!='enum');
        
    },
    /**
     * 
     * @param {*} data 
     */
    saveHandler:function saveHandler(data)
    {
        //schema存储
        console.log(data);
    } 

},function (type) {

});
 